import React, { useEffect } from 'react';
import { Button, DatePicker, Select, Space } from 'antd';
import _ from 'lodash';
import moment from 'moment';

import { useTRState } from '#/utils/trHooks.jsx';
import { TjSegmented } from '@/pages/ETrade/components';
import { dateTypeOptions, viewTypeOptions, typeOptions } from './helper';
import styles from './index.less';

const getAllStation = (data) => _.flattenDeep(data?.map((a) => a?.children));
const defaultForm = (market) => {
  const stations = getAllStation(market?.children || []);
  return {
    market, // 交易中心信息
    stations, // 场站列表
    dateType: 0, // 日期类型 0:自定义类型 1:固定类型
    dayMonthPoint: 0, // 0:每日 1:每月 2:每时点 3:每周
    viewType: 0, // 视图类型 0:年度类型 1:季度类型 2:月度类型
    year: moment().add(-1, 'y'), // 年
    quarter: moment().add(-1, 'Q'), // 季度
    month: moment().add(-1, 'month'), // 月
    openDates: null,
    dates: [moment().add(-1, 'year'), moment()], // 默认过去一年
    type: '96', // 24 96
  };
};

export default ({ power, loading = false, onChange = () => {}, market, setIsRe }) => {
  // const markets = power.filter((x) => x.value !== 'PXBMX');
  const markets = power;
  /** data */
  const [state, setState] = useTRState({
    ...defaultForm(market || markets[0]),
    isFetch: false, // 控制是否触发查询
  });

  useEffect(() => {
    onFinish();
  }, [state.isFetch]);

  /** methods */
  const onFinish = () => {
    const { dateType, dayMonthPoint, type, viewType } = state;
    const provinceId = state.market.provinceId;
    const marketId = state.market.value;
    let params = {
      dateType,
      dayMonthPoint,
      provinceId,
      marketId,
      type,
    };
    let subTitle = '';
    const dayMonthPointLab = ['每日', '每月', '时点统计', '每周'][dayMonthPoint] || '';
    const viewLab = ['年度', '季度', '月度'][viewType] || '';
    let dayRange = [];
    if (dateType === 0) {
      const titleDates = [
        moment(state.dates[0]).format('YYYYMMDD'),
        moment(state.dates[1]).format('YYYYMMDD'),
      ];
      subTitle = `${titleDates[0]}-${titleDates[1]} ${dayMonthPointLab}`;
      params.startDate = moment(state.dates[0]).format('YYYY-MM-DD');
      params.endDate = moment(state.dates[1]).format('YYYY-MM-DD');
      dayRange = [params.startDate, params.endDate];
    } else if (dateType === 1) {
      subTitle = `${viewLab}${dayMonthPointLab}`;
      params.viewType = viewType;
      if (viewType === 0) {
        let _date = moment(state.year);
        params.yearQuarterMonth = _date.format('YYYY');
        dayRange = fmtRange(_date, 'year', 'YYYY-MM-DD');
      } else if (viewType === 1) {
        let _date = moment(state.quarter);
        params.yearQuarterMonth = _date.format('YYYY-Q');
        dayRange = fmtRange(_date, 'quarter', 'YYYY-MM-DD');
      } else if (viewType === 2) {
        let _date = moment(state.month);
        params.yearQuarterMonth = _date.format('YYYY-MM');
        dayRange = fmtRange(_date, 'month', 'YYYY-MM-DD');
      }
    }
    if (typeof onChange === 'function') {
      const { market, stations } = state;
      onChange?.(params, {
        market, // 交易中心信息
        stations, // 场站列表
        subTitle, // 动态标题拼接
        dayRange,
      });
    }
  };

  const onReset = () => {
    setState({
      ...defaultForm(market || markets[0]),
      isFetch: !state.isFetch,
    });
    setIsRe();
  };

  function fmtRange(mo, type, fmt) {
    return [mo.startOf(type).format(fmt), mo.endOf(type).format(fmt)];
  }

  /** render */
  return (
    <Space size={16} wrap>
      <Select
        style={{ width: 200 }}
        value={state.market.value}
        options={markets}
        optionFilterProp="label"
        showSearch
        showArrow
        onChange={(v, market) => {
          const stations = getAllStation(market?.children || []);
          setState({ market, stations });
        }}
      />
      <TjSegmented
        value={state.dateType}
        options={dateTypeOptions}
        onChange={(dateType) =>
          setState({
            dateType,
            dayMonthPoint: 0,
            viewType: 0,
          })
        }
      />
      {/* 自定义时间范围 */}
      {state.dateType === 0 && (
        <>
          <DatePicker.RangePicker
            style={{ width: 216 }}
            value={state.openDates || state.dates}
            separator="-"
            format={'YYYYMMDD'}
            allowClear={false}
            disabledDate={(v) => v > moment()}
            onChange={(dates) => {
              setState({
                dates,
                dayMonthPoint: 0,
              });
            }}
            onCalendarChange={(openDates) => setState({ openDates })}
            onOpenChange={(open) => setState({ openDates: open ? [null, null] : null })}
            getPopupContainer={(e) => e.parentNode}
          />
          <Select
            style={{ width: 120 }}
            value={state.dayMonthPoint}
            showArrow
            getPopupContainer={(e) => e.parentNode}
            onChange={(dayMonthPoint) => {
              // if (dayMonthPoint === 1) {
              //   setState({ dates: [moment().add(-11, 'month'), moment()], dayMonthPoint });
              // } else {
              //   setState({ dayMonthPoint });
              // }
              setState({ dayMonthPoint });
            }}
          >
            {state.dates[1].diff(state.dates[0], 'days') > 29 && (
              <Select.Option value={1}>每月</Select.Option>
            )}
            <Select.Option value={3}>每周</Select.Option>
            <Select.Option value={0}>每日</Select.Option>
            {(state.market?.value === 'PXBGS' || state.market?.value === 'PXBMX') && (
              <Select.Option value={2}>时点统计</Select.Option>
            )}
          </Select>
        </>
      )}
      {/* 固定日期 */}
      {state.dateType === 1 && (
        <>
          <Select
            style={{ width: 120 }}
            value={state.viewType}
            options={viewTypeOptions}
            getPopupContainer={(e) => e.parentNode}
            onChange={(viewType) =>
              setState({
                viewType,
                dayMonthPoint: 0,
              })
            }
          />
          {state.viewType === 0 && (
            <DatePicker
              value={state.year}
              style={{ width: 120 }}
              picker="year"
              format={'YYYY'}
              disabledDate={(v) => v > moment().startOf('year')}
              getPopupContainer={(e) => e.parentNode}
              allowClear={false}
              onChange={(year) => setState({ year })}
            />
          )}
          {state.viewType === 1 && (
            <DatePicker
              value={state.quarter}
              style={{ width: 120 }}
              picker="quarter"
              className={styles.quarterPickerBox}
              dropdownClassName={styles.quarterPicker}
              disabledDate={(v) => v > moment().startOf('quarter')}
              getPopupContainer={(e) => e.parentNode}
              allowClear={false}
              onChange={(quarter) => setState({ quarter })}
            />
          )}
          {state.viewType === 2 && (
            <DatePicker
              value={state.month}
              style={{ width: 120 }}
              picker="month"
              format={'YYYYMM'}
              disabledDate={(v) => v > moment().startOf('month')}
              getPopupContainer={(e) => e.parentNode}
              allowClear={false}
              onChange={(month) => setState({ month })}
            />
          )}
          <Select
            style={{ width: 120 }}
            value={state.dayMonthPoint}
            showArrow
            getPopupContainer={(e) => e.parentNode}
            onChange={(dayMonthPoint) => setState({ dayMonthPoint })}
          >
            {state.viewType !== 2 && <Select.Option value={1}>每月</Select.Option>}
            <Select.Option value={0}>每日</Select.Option>
            <Select.Option value={2}>时点统计</Select.Option>
          </Select>
        </>
      )}
      <TjSegmented
        value={state.type}
        options={typeOptions}
        onChange={(type) => setState({ type })}
      />
      <Space>
        <Button
          style={{ width: 98, height: 32 }}
          type="primary"
          disabled={loading}
          onClick={onFinish}
        >
          查询
        </Button>
        <Button style={{ width: 98, height: 32 }} ghost onClick={onReset}>
          重置
        </Button>
      </Space>
    </Space>
  );
};
